<template>
  <Form
    span="24"
    :columns="columns"
    ref="form"
    labelWidth="100px"
    :formData="formData"
  >
    <template #group1>
      <van-cell-group title="基本信息" />
    </template>
    <template #group2>
      <van-cell-group title="血压（mmHg)和心率（次/分钟）" />
    </template>
    <template #group3>
      <van-cell-group title="动态血压监测(选填)" />
    </template>
    <template #group4>
      <van-cell-group title="病史" />
    </template>
    <template #group5>
      <van-cell-group title="实验室指标" />
    </template>
    <template #group6>
      <van-cell-group title="诊断" />
    </template>
    <template #group7>
      <van-cell-group title="用药：（没有相关用药写无）" />
    </template>
  </Form>
  <van-button @click="onSubmit" block type="primary">提交</van-button>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Form } from '@hanyk/v3-form'
import { showToast, showLoadingToast, closeToast } from 'vant'
import 'vant/es/toast/style'
import { columns, defaultValues } from './fomConfig'
import axios from 'axios'
const form = ref()
let formData = ref({ ...defaultValues })
watch(
  [() => formData.value.height, () => formData.value.weight],
  ([height, weight]) => {
    if (height && weight) {
      let h = Number(height)
      let w = Number(weight)
      if (isNaN(h) || isNaN(w)) {
        return
      }

      formData.value.bmi = (w / ((h / 100) * (h / 100))).toFixed(2)
    }
  }
)
const onSubmit = async () => {
  try {
    const data = await form.value.validate()
    showLoadingToast('提交中...')
    axios
      .post('/service/xueya/add', data)
      .then(res => {
        closeToast()
        if (res.status === 200 && res.data.code === '200') {
          showToast('提交成功')
          formData.value = { ...defaultValues }
        } else {
          showToast(res.data.message ?? '提交失败')
        }
      })
      .catch(err => {
        closeToast()
        showToast(err.message)
      })
  } catch (error) {
    showToast({
      message: '请填写完整信息',
      overlay: true
    })
  }
}
</script>
<style lang="less">
.v3-form {
  padding: 12px !important;
}
.v3-form-item {
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
  .van-cell-group__title {
    background-color: #f0f2f5;
  }
  .van-cell:after {
    border-bottom: none;
  }
  .v3-form-item-label {
    white-space: pre-wrap;
  }
}
</style>
